package com.handong.handserialprogram.module.setring;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.handong.handserialprogram.R;
import com.handong.handserialprogram.constants.KeyConstant;
import com.handong.handserialprogram.model.entities.CriminalEntity;
import com.handong.handserialprogram.model.entities.FootRingNewEntity;
import com.handong.handserialprogram.module.base.BaseActivity;
import com.handong.handserialprogram.ui.radar.RadarScanView;
import com.handong.handserialprogram.utils.AppUtil;
import com.handong.handserialprogram.utils.AsyncHttpUtil;
import com.handong.handserialprogram.utils.UserGuideUtil;
import com.handong.handserialprogram.utils.ViewUtil;
import com.handong.handserialprogram.widget.guideview.Guide;
import com.handong.handserialprogram.widget.guideview.GuideBuilder;

import java.util.ArrayList;
import java.util.List;

import static com.handong.handserialprogram.utils.AppCache.getContext;

/**
 * 设置脚环-查找附近脚环
 */
public class SetRingActivity extends BaseActivity<SetRingPresenter> implements SetRingContract.View {

    private static final String TAG = "SetRingActivity";

    private RecyclerView mSetRingRV;
    private RadarScanView mRadarScan;
    private TextView mSearchResult;

    private RingListAdapter mRingAdapter;
    private CriminalEntity mCriminalEntity;

    private MaterialDialog mBindDialog = null;

    private boolean isFirstGuide = true;

    private Guide mGuideInstance;

    private String mMissID;


    @Override
    protected int getContentViewID() {
        return R.layout.activity_set_ring;
    }

    @Override
    protected SetRingPresenter createPresenter() {
        return new SetRingPresenter(this);
    }

    @Override
    protected void initViewByID() {
        initHeaderLayout(false);
        //setOptionItem("确定");
        setCenterTitle("设置犯人脚环");
        mSetRingRV = (RecyclerView) findViewById(R.id.setRingRecyclerView);
        mRadarScan = (RadarScanView) findViewById(R.id.setRingRadarScan);

        mSearchResult = (TextView) findViewById(R.id.searchFootRingResult);
    }

    @Override
    protected void initViewDataRes() {
        mPresenter.scanAroundFootRing();//扫描脚环
        Bundle bundle = getIntent().getExtras();
        if (bundle != null || !bundle.isEmpty()) {
            mCriminalEntity = bundle.getParcelable(KeyConstant.SINGLE_PERSON);
            mMissID = bundle.getString(KeyConstant.MISSION_ID);
            ArrayList<CriminalEntity> mCriminalEntitys= (ArrayList<CriminalEntity>) bundle.getSerializable(KeyConstant.CRIMINALS_LIST);
            mPresenter.setPersonEntityList(mCriminalEntitys);
        }
        if(mCriminalEntity==null) finish();
        if(TextUtils.isEmpty(mMissID)) finish();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.headerBackLayout:
                finish();
                break;

            case R.id.headerOptionLayout:

                break;

            default:
                super.onClick(v);
        }
    }

    /**
     * 绑定脚环
     * @param entity
     */
    public void uploadPersonBindInfo(final FootRingNewEntity entity) {
        if (mBindDialog == null) {
            View contentView = LayoutInflater.from(this).inflate(R.layout.dialog_bind_ring, null);
            TextView ringInfo = (TextView) contentView.findViewById(R.id.dialogRingInfo);
            TextView personInfo = (TextView) contentView.findViewById(R.id.dialogPersonInfo);
            ringInfo.setText("选中脚环编号：" + entity.getRingID());
            personInfo.setText("需要设置的人员：" + mCriminalEntity.getPName());
            final Context context=this;
            mBindDialog = new MaterialDialog.Builder(this)
                    .title("设置脚环")
                    .customView(contentView, true)
                    .positiveColorRes(R.color.back_ground_green)
                    .positiveText("绑定")
                    .negativeColorRes(R.color.dialog_bg)
                    .negativeText(R.string.dialog_negative_text)
                    .autoDismiss(false)
                    .canceledOnTouchOutside(false)
                    .onNegative(new MaterialDialog.SingleButtonCallback() {
                        @Override
                        public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                            dialog.dismiss();
                            mCriminalEntity.setRingEntity(null);
                        }
                    })
                    .onPositive(new MaterialDialog.SingleButtonCallback() {
                        @Override
                        public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                            dialog.dismiss();
                            mCriminalEntity.setRingEntity(entity);

                            if (AsyncHttpUtil.isNetworkConnected(context)) {
                                showLoadDialog("正在上传脚环信息...");
                                mPresenter.uploadBingRingInfo(mCriminalEntity, mMissID);
                            } else {
                                AppUtil.showShortToast(context, "网络连接错误");
                                //mPresenter.uploadBingRingInfo(mCriminalEntity, mMissID);
                            }
                        }
                    }).build();
        } else {
            LinearLayout container = (LinearLayout) mBindDialog.getCustomView();
            TextView ring = (TextView) container.getChildAt(0);
            ring.setText("选中脚环：" + entity.getRingID());
            TextView person = (TextView) container.getChildAt(1);
            person.setText("需要绑定人员：" + mCriminalEntity.getPName());
        }
        ViewUtil.removeHomeKeyListener(mBindDialog);
    }

    /*protected void showBindRingDialog(final FootRingNewEntity entity) {
        LinearLayout container = new LinearLayout(this);
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT);
        container.setOrientation(LinearLayout.VERTICAL);
        float dpi = SystemUtil.displayMetricsDpi(this);
        container.setPadding(Math.round(4 * dpi), 0, Math.round(10 * dpi), 0);
        container.setLayoutParams(params);

        TextView person = new TextView(this);
        LinearLayout.LayoutParams personParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT);
        personParams.bottomMargin = Math.round(5 * dpi);
        person.setLayoutParams(personParams);
        person.setTextSize(16);
        person.setText("需要绑定人员：" + mCriminalEntity.getPName());

        TextView ring = new TextView(this);
        LinearLayout.LayoutParams ringParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT);
        ringParams.topMargin = Math.round(7 * dpi);
        ring.setLayoutParams(ringParams);
        ring.setTextSize(16);
        ring.setText("选中脚环：" + entity.getRingID());
        container.addView(ring);
        container.addView(person);

        MaterialDialog dialog = new MaterialDialog.Builder(this)
                .title("绑定脚环")
                .customView(container, true)
                .positiveColorRes(R.color.back_ground_green)
                .positiveText("绑定")
                .negativeColorRes(R.color.dialog_bg)
                .negativeText(R.string.dialog_negative_text)
                .autoDismiss(false)
                .canceledOnTouchOutside(false)
                .onNegative(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        dialog.dismiss();
                        mCriminalEntity.setRingEntity(null);
                    }
                })
                .onPositive(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        dialog.dismiss();
                        mCriminalEntity.setRingEntity(entity);
                        showLoadDialog("正在上传脚环信息...");
                        if (AsyncHttpUtil.isNetworkConnected(getContext())) {
                            mPresenter.uploadBingRingInfo(mCriminalEntity, mMissID);
                        } else {
                            mPresenter.uploadBingRingInfo(mCriminalEntity, mMissID);
                        }
                    }
                }).build();
        ViewUtil.removeHomeKeyListener(dialog);
    }*/

    /**
     * 绑定成功
     */
    public void bindPersonInfoSuccess() {
        dismissLoadingDialog();
        AppUtil.showShortToast(this, "绑定成功");

        Intent intent = new Intent();
        Bundle bundle = new Bundle();
        bundle.putParcelable(KeyConstant.SINGLE_PERSON,
                mCriminalEntity.getRingEntity());
        intent.putExtras(bundle);
        setResult(KeyConstant.INDEX_1, intent);
        finish();
    }
    /**
     * 绑定失败
     */
    public void bindPersonInfoFail(String reason) {
        dismissLoadingDialog();
        uploadPersonBindInfo(mCriminalEntity.getRingEntity());
        AppUtil.showShortToast(this, reason);
        //if (mBindDialog != null) {
        //    mBindDialog.show();
        //}
    }

    /**
     * 显示脚环列表
     */
    @Override
    public void showFootRingList(List<FootRingNewEntity> list) {

        if (!list.isEmpty()) {
            if(mRadarScan.isShown()){
                mRadarScan.stopAnimation();
                mRadarScan.setVisibility(View.GONE);
                mSetRingRV.setVisibility(View.VISIBLE);
            }
        }else{
            if(!mRadarScan.isShown()){
                mRadarScan.startAnimation();
                mRadarScan.setVisibility(View.VISIBLE);
            }
            mSetRingRV.setVisibility(View.GONE);
        }
       /* if (mRadarScan != null && mRadarScan.isShown()) {
            mRadarScan.stopAnimation();
            mRadarScan.onDestroy();
            RelativeLayout layout = (RelativeLayout) mRadarScan.getParent();
            layout.removeView(mRadarScan);
            layout.removeView(mSearchResult);
            mRadarScan = null;
        }*/

      /*  if (list == null || list.size() == 0) {
            return;
        }*/
        if (mRingAdapter == null) {
            mRingAdapter = new RingListAdapter(list, this);
            mSetRingRV.setLayoutManager(new LinearLayoutManager(this));
            mSetRingRV.setAdapter(mRingAdapter);
        } else {
            mRingAdapter.notifyDataSetChanged();
        }

        mSetRingRV.setVisibility(View.VISIBLE);
    }

    /**
     * 激活脚环
     */
    public void activateFootRing(String id) {
        mPresenter.activateFootRing(id);
    }

    /**
     * 脚环自检错误
     */
    public void showCheckDialog(final String paramString,final String errorString) {
        ViewUtil.removeHomeKeyListener(new MaterialDialog.Builder(this)
                .content("脚环"+paramString+"自检失败，详情："+errorString)
                .negativeColorRes(R.color.dialog_bg)
                .negativeText(R.string.dialog_negative_text)
                .build());
    }

    /**
     * 激活失败
     */
    public void activateRingError(final String id) {
        dismissLoadingDialog();
        ViewUtil.removeHomeKeyListener(new MaterialDialog.Builder(this)
                .content("激活脚环失败，是否重试？")
                .negativeText(R.string.dialog_negative_text)
                .negativeColorRes(R.color.dialog_bg)
                .positiveText(R.string.dialog_positive_again)
                .positiveColorRes(R.color.back_ground_green)
                .onPositive(new MaterialDialog.SingleButtonCallback() {
                    public void onClick(@NonNull MaterialDialog paramAnonymousMaterialDialog, @NonNull DialogAction paramAnonymousDialogAction) {
                        mPresenter.activateFootRing(id);
                    }
                }).build());
    }
    /**
     * 激活成功 上传数据
     */
    public void activateRingSuccess(FootRingNewEntity entity) {
        showLoadDialog("正在上传脚环数据...");
        mCriminalEntity.setRingEntity(entity);
        mPresenter.uploadBingRingInfo(mCriminalEntity, mMissID);//激活成功自动绑定
    }

    /**
     * 退出脚环
     */
    public void logoutSuccess() {
        //AppUtil.showShortToast(this, "脚环已休眠");
        finish();
    }

    public void logoutFail(final String paramString) {
        ViewUtil.removeHomeKeyListener(new MaterialDialog.Builder(this)
                .content("休眠脚环失败")
                .negativeColorRes(R.color.dialog_bg)
                .positiveText(R.string.dialog_positive_sleep)
                .positiveColorRes(R.color.back_ground_green)
                .negativeText("直接退出")
                .onPositive(new MaterialDialog.SingleButtonCallback() {
                    public void onClick(@NonNull MaterialDialog paramAnonymousMaterialDialog, @NonNull DialogAction paramAnonymousDialogAction) {
                        mPresenter.logoutFootRing(paramString);
                    }
                }).onNegative(new MaterialDialog.SingleButtonCallback() {
                    public void onClick(@NonNull MaterialDialog paramAnonymousMaterialDialog, @NonNull DialogAction paramAnonymousDialogAction) {
                        mPresenter.forceExit(paramString);
                        SetRingActivity.this.finish();
                    }
                }).build());
    }

    /**
     * 脚环SIM出错
     */
    protected void simInitError(final String missID) {
        ViewUtil.removeAllKeyListener(new MaterialDialog.Builder(this)
                .title(R.string.dialog_title_problem)
                .content("脚环:" + missID + " 获取Sim卡信息失败\n\n请注销重新检查！")
                .positiveText(R.string.dialog_positive_sleep)
                .canceledOnTouchOutside(false)
                .positiveColorRes(R.color.back_ground_green)
                .onPositive(new MaterialDialog.SingleButtonCallback() {
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction dialogAction) {
                        mPresenter.logoutFootRing(missID);
                    }
                }).build());
    }

    @Override
    public void showNoFootRingAround() {
        if (!mSearchResult.isShown()) {
            //mRadarScan.stopAnimation();
            mSearchResult.setVisibility(View.VISIBLE);
            mSearchResult.setText("请将脚环靠近手持机");
            //mSearchResult.setOnClickListener(this);
        } else {
            //mSearchResult.setText("无可用脚环");
            //mRadarScan.stopAnimation();
        }
    }

    public CriminalEntity getCriminalEntity() {
        return this.mCriminalEntity;
    }

    public boolean isFirstGuide() {
        return this.isFirstGuide;
    }

    public void setFirstGuide(boolean firstGuide) {
        isFirstGuide = firstGuide;
    }

    /**
     * 执行任务前,请先激活脚环 引导
     */
    public void showActivateGuideView(View guideView, int resID) {
        mGuideInstance = UserGuideUtil.showActivateGuideView(guideView, resID, this,
                new GuideBuilder.OnVisibilityChangedListener() {
                    @Override
                    public void onShown() {
                    }

                    @Override
                    public void onDismiss() {
                        mGuideInstance = null;
                    }
                });
    }

    /**
     * 脚环已激活，可点击与犯人绑定到一起！
     */
    public void showItemGuide(int posstion) {
        mGuideInstance = UserGuideUtil.showRingItemBandGuide(mRingAdapter.getView(posstion), R.id.ringItemContainer, this,
                new GuideBuilder.OnVisibilityChangedListener() {
                    @Override
                    public void onShown() {
                    }

                    @Override
                    public void onDismiss() {
                        mGuideInstance = null;
                    }
                });
    }

    /**
     * 休眠脚环并推出
     */
    public void showExitDialog(final String paramString) {
        ViewUtil.removeHomeKeyListener(new MaterialDialog.Builder(this).content("是否休眠脚环并退出？")
                .negativeColorRes(R.color.dialog_bg)
                .positiveText("休眠")
                .positiveColorRes(R.color.back_ground_green)
                .negativeText(R.string.dialog_negative_text)
                .onPositive(new MaterialDialog.SingleButtonCallback() {
                    public void onClick(@NonNull MaterialDialog paramAnonymousMaterialDialog, @NonNull DialogAction paramAnonymousDialogAction) {
                        mPresenter.logoutFootRing(paramString);
                    }
                }).build());
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        if (KeyEvent.KEYCODE_BACK == keyCode && mGuideInstance != null
                && mGuideInstance.onKey(null, keyCode, event)) {
            return true;
        }
        return super.onKeyUp(keyCode, event);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                finish();
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void finish() {
        if (!mPresenter.isCanExit()) {
            return;
        }
        super.finish();
        overridePendingTransition(R.anim.anim_no, R.anim.push_right_out);
    }

    @Override
    protected void onDestroy() {
        if (mRadarScan != null) {
            mRadarScan.stopAnimation();
            mRadarScan.onDestroy();
            mRadarScan = null;
        }
        if (mBindDialog != null) {
            mBindDialog.cancel();
            mBindDialog = null;
        }
        super.onDestroy();
    }
}
